package cloud

import (
	"dgo/MyProj/PrjHttpUtils"
	"dgo/goutils/utils"
	"dgo/plg/plgnet"
	"gitee.com/ymofen/supervalue"
	"time"
)

type VxApiWrapper struct {
	PlgBase
	msglst       *utils.SyncCycleList
	templmsg_url string
}

/*
*

	{
	  "id": "vxapi",
	  "type": "cloud.vx.api.wrapper",
	  "conf": {
	     "templmsg-url":"",
	  }
	}
*/
func (this *VxApiWrapper) ReloadConf(conf *wrapper.SuperValue) error {
	if conf == nil {
		return nil
	}

	if this.msglst == nil {
		this.msglst = utils.NewSyncCycleList()
	}

	this.templmsg_url = conf.StringByName("templmsg-url", "")

	utils.DefaultPatrolTask().AddTask(this, time.Second*30, func(id interface{}, args ...interface{}) {
		//utils.DefaultWorkers().PostTaskFunc(this, this.innerWork)
	})
	return nil
}

func (this *VxApiWrapper) Close() (err error) {
	this.PlgBase.Close()
	utils.DefaultPatrolTask().DelTask(this)
	return
}

func (this *VxApiWrapper) OnHttpStatus(rec *plgnet.PlgHttpRec) (rval interface{}, errcode int, err error) {
	itype := rec.QryAsInt("type", 0)
	if itype == 99 {
		json := wrapper.NewSVObject()
		json.SetKeyValue("templmsg-url", this.templmsg_url)
		json.SetKeyValues("now", utils.NowString())
		PrjHttpUtils.JSON2TableRec(rec.RespW, "", json.AsJSONString(false))
	} else if itype == 98 {
		rec.ResponseSyncListNEx(this.msglst)
	} else if itype == 1 {
		//searchval := rec.QryAsString("searchval", "")
		json := wrapper.NewSVArray()
		//this.lstDevice.ListRangeV2(func(key, value interface{}) bool {
		//	//dev := value.(*YsledMqttWebServDevice)
		//	ok := true
		//	if len(searchval) > 0 {
		//
		//	}
		//	return ok
		//}, func(k0, v0, k1, v1 interface{}) bool {
		//	return true
		//}, func(key, val interface{}) bool {
		//	return true
		//})

		if rec.QryAsInt("json", 0) == 1 {
			PrjHttpUtils.ResponseAsJSON(rec.RespW, json.AsJSONStringEx(false, false))
		} else {
			PrjHttpUtils.JSON2Table(rec.RespW, "", json.AsJSONString(false))
		}
	} else {
		var sb utils.BytesBuilder
		PrjHttpUtils.AppendIndexBody(&sb, "status", "status?type=99")
		PrjHttpUtils.AppendIndexBody(&sb, "msglist", "status?type=98&n=100&searchval=")
		PrjHttpUtils.ResponseBodyHtml(rec.RespW, sb.String())
	}
	return
}

func (this *VxApiWrapper) LogInfoMessage(s string, args ...interface{}) {
	this.msglst.LogMsg(s, args...)
	utils.Log.Msgf(this.PlugId, utils.LogLV_INFO, 1, s, args...)
}

func (this *VxApiWrapper) LogWarnMessage(s string, args ...interface{}) {
	this.msglst.LogMsg(s, args...)
	utils.Log.Msgf(this.PlugId, utils.LogLV_WARN, 1, s, args...)
}

func CreateVxApiWrapperFunc(args ...interface{}) (rval interface{}, err error) {
	obj := &VxApiWrapper{}

	if len(args) > 0 {
		if str, ok := args[0].(string); ok {
			obj.PlugId = str
		}
	}
	rval = obj
	return
}
